/*===========================================================
 
 .---=||||[ B L O O D Y ]|||||=====================----------....
 |                                                              |
 |    THE  M O S T   B L O O D Y  GAME EVER!                    |
 |                                                              |
 |    bloody harvest is coming... soon,                         |
 |                                              heil Satan!     |
 !                                                              !
 .                                                              ,
  ~~~~-------------================================|||||||||==-~




 Name-Space: {core, logic, editor}
 Module: {draw, coll, scgr, ...}
 Class: <name of class>
 Last modification:  <author>, <time>

 TODO:
 <-------- todo #1 ---------->
 <-------- todo #2 ---------->
 <-------- todo #3 ---------->
        ............
 <-------- todo #n ---------->

 FIX:
 <-------- fix #1 ----------->
 <-------- fix #1 ----------->
         ..........
 <-------- fix #n ----------->




 
 
 ============================================================*/

#include <iostream>
#include <sstream>
#include "core/Config.h"
#include "core/exceptions.h"

using namespace std;

namespace core
{
	
	Config::Config(const String& fileNam)
		: fileName(fileNam)
	{

		ifstream fs(fileName.c_str());
		if (!fs.good())
			throw FileNotFoundException(fileName.c_str());
		while(!fs.eof())
		{
			char buf[256];
			fs.getline(buf, 256);
			string line(buf);
				
	
			if (line[0] == '#' || line == "")
				continue;
				
			// strip comments at the end of line
			int idx = line.find('#', 0);
			if (idx >= 0)
			{
				line = line.substr(0, idx);
			}
			
			idx = line.find('=', 0);
				
			string name = line.substr(0,idx);
			string value = line.substr(idx+1);
			name = trim(name);
			value = trim(value);
			//cout << name << "=" << value << endl;
			data.insert(pair<string,Item>(name, Item(name, value)));
		}
			
		fs.close();
	}
	
	const Config::Item& Config::operator[](string name) const
	{
		map<string, Item>::const_iterator it = data.find(name);
		if (it == data.end())
			throw BaseException("Key \"%s\" not found in config file %s", name.c_str(), fileName.c_str());
		return (*it).second;
	}
	
	bool Config::hasKey(string name) const
	{
		return data.find(name) != data.end();
	}
	
	string Config::trim(string str)
	{
		string ret = str;
		unsigned idx = 0;
		
		// find first not-space character in string
		for (; (ret[idx] == ' ' || ret[idx] == '\t') && idx < ret.length(); idx++);
		// remove spaces before not-space first
		if (idx > 0)
			ret = ret.substr(idx);
		
		// find last not-psace character in string
		for(idx = ret.length() - 1; (ret[idx] == ' ' || ret[idx] == '\t') && idx >= 0; idx--);
		// remove spaces after last not-space chracter
		if (idx < ret.length() - 1)
			ret = ret.substr(0, idx + 1);
			
		return ret;
	}
	
	
	
}

